package com.ysd.lis.service.emr.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.lis.dto.emr.EmrVersionTree;
import com.ysd.lis.entity.emr.EmrItem;
import com.ysd.lis.entity.emr.EmrItemStandard;
import com.ysd.lis.entity.emr.EmrVersion;
import com.ysd.lis.entity.emr.EmrVersionRole;
import com.ysd.lis.mapper.emr.EmrVersionMapper;
import com.ysd.lis.request.emr.EmrVersionVo;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.emr.EmrItemService;
import com.ysd.lis.service.emr.EmrItemStandardService;
import com.ysd.lis.service.emr.EmrVersionRoleService;
import com.ysd.lis.service.emr.EmrVersionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wh
 * @since 2025-06-04
 */
@Service
public class EmrVersionServiceImpl extends ServiceImpl<EmrVersionMapper, EmrVersion> implements EmrVersionService {


    @Autowired
    private EmrVersionRoleService emrVersionRoleService;
    @Autowired
    private EmrItemService emrItemService;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    EmrItemStandardService emrItemStandardService;

    @Override
    public Result saveOrEditVersion(EmrVersionVo emrVersionVo) {
        this.remove(new LambdaQueryWrapper<EmrVersion>().eq(EmrVersion::getVersionCode, emrVersionVo.getVersionCode()));
        emrVersionRoleService.remove(new LambdaQueryWrapper<EmrVersionRole>().eq(EmrVersionRole::getVersionCode, emrVersionVo.getVersionCode()));
        EmrVersion emrVersion = new EmrVersion();
        BeanUtils.copyProperties(emrVersionVo, emrVersion);
        boolean save = this.save(emrVersion);
        if (CollectionUtil.isNotEmpty(emrVersionVo.getRoles())) {
            List<EmrVersionRole> emrVersionRoles = emrVersionVo.getRoles().stream().map(role -> {
                EmrVersionRole emrVersionRole = new EmrVersionRole();
                String[] split = role.split("-");
                emrVersionRole.setRoleCode(split[0]);
                emrVersionRole.setRoleName(split[1]);
                emrVersionRole.setVersionCode(emrVersionVo.getVersionCode());
                return emrVersionRole;
            }).collect(Collectors.toList());
            emrVersionRoleService.saveBatch(emrVersionRoles);
        }
        if (save) {
            return Result.succ(1, "操作成功", emrVersion);
        } else {
            return Result.succ(400, "操作失败", "");
        }
    }

    @Override
    public Result deleteVersionDetail(EmrVersionTree emrVersionTree) {
        if (emrVersionTree.getType().equals("1")) {
            this.removeById(emrVersionTree.getId());
            emrVersionRoleService.remove(new LambdaQueryWrapper<EmrVersionRole>().eq(EmrVersionRole::getDelFlag, 0).eq(EmrVersionRole::getVersionCode, emrVersionTree.getCode()));
            emrItemService.remove(new LambdaQueryWrapper<EmrItem>().eq(EmrItem::getDelFlag, 0).eq(EmrItem::getVersionCode, emrVersionTree.getCode()));
            emrItemStandardService.remove(new LambdaQueryWrapper<EmrItemStandard>().eq(EmrItemStandard::getDelFlag, 0).eq(EmrItemStandard::getVersionCode, emrVersionTree.getCode()));
        } else {
            emrVersionRoleService.removeById(emrVersionTree.getId());
            emrItemService.remove(new LambdaQueryWrapper<EmrItem>().eq(EmrItem::getDelFlag, 0).eq(EmrItem::getVersionCode, emrVersionTree.getPCode()).eq(EmrItem::getRoleCode, emrVersionTree.getCode()));
            emrItemStandardService.remove(new LambdaQueryWrapper<EmrItemStandard>().eq(EmrItemStandard::getDelFlag, 0).eq(EmrItemStandard::getVersionCode, emrVersionTree.getPCode()).eq(EmrItemStandard::getRoleCode, emrVersionTree.getCode()));
        }
        return Result.succ(1, "成功", "");
    }

    @Override
    public Result getVersionRolesTree() {
        List<Map<String, Object>> emrTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("emrType").getData();
        //转成map code是key name是value
        Map<String, String> emrTypeMap = emrTypeList.stream().collect(Collectors.toMap(map -> (String) map.get("code"), map -> (String) map.get("name")));

        List<EmrVersion> versionList = this.list(new LambdaQueryWrapper<EmrVersion>().eq(EmrVersion::getDelFlag, 0).orderByAsc(EmrVersion::getSeq));
        List<EmrVersionRole> versionRoles = emrVersionRoleService.list(new LambdaQueryWrapper<EmrVersionRole>().eq(EmrVersionRole::getDelFlag, 0));
        Map<String, List<EmrVersionRole>> roleMap = versionRoles.stream().collect(Collectors.groupingBy(EmrVersionRole::getVersionCode));
        roleMap.forEach((versionCode, roleList) -> {
            roleList.sort(Comparator.comparing(EmrVersionRole::getRoleCode));
        });
        List<EmrVersionTree> list = new ArrayList<>();
        for (EmrVersion emrVersion : versionList) {
            EmrVersionTree emrVersionTree = new EmrVersionTree();
            emrVersionTree.setId(emrVersion.getId());
            emrVersionTree.setCode(emrVersion.getVersionCode());
            emrVersionTree.setName(emrVersion.getVersionName());
            emrVersionTree.setEmrType(emrVersion.getEmrType());
            emrVersionTree.setEmrTypeName(emrTypeMap.get(emrVersion.getEmrType()));
            emrVersionTree.setSeq(emrVersion.getSeq());
            emrVersionTree.setType("1");
            if (roleMap.containsKey(emrVersion.getVersionCode())) {
                List<EmrVersionTree> emrVersionTrees = new ArrayList<>();
                for (EmrVersionRole emrVersionRole : roleMap.get(emrVersion.getVersionCode())) {
                    EmrVersionTree emrVersionTree1 = new EmrVersionTree();
                    emrVersionTree1.setId(emrVersionRole.getId());
                    emrVersionTree1.setPCode(emrVersion.getVersionCode());
                    emrVersionTree1.setCode(emrVersionRole.getRoleCode());
                    emrVersionTree1.setName(emrVersionRole.getRoleName());
                    emrVersionTree1.setType("2");
                    emrVersionTrees.add(emrVersionTree1);
                }
                emrVersionTree.setChildren(emrVersionTrees);
            }
            list.add(emrVersionTree);
        }
        return Result.succ(1, "成功", list);
    }

    @Override
    public Result getRolseItemByVersion(String versionCode) {
        if (StringUtils.isBlank(versionCode)) {
            return Result.fail("版本号不能为空");
        }
        List<EmrVersionTree> list = new ArrayList<>();
        List<EmrVersionRole> versionRoles = emrVersionRoleService.list(new LambdaQueryWrapper<EmrVersionRole>().eq(EmrVersionRole::getDelFlag, 0).eq(EmrVersionRole::getVersionCode, versionCode).orderByAsc(EmrVersionRole::getRoleCode));
        List<EmrItem> emrItems = emrItemService.list(new LambdaQueryWrapper<EmrItem>().eq(EmrItem::getDelFlag, 0).eq(EmrItem::getVersionCode, versionCode));
        Map<String, List<EmrItem>> itemMap = emrItems.stream().collect(Collectors.groupingBy(EmrItem::getRoleCode));


        for (EmrVersionRole emrVersionRole : versionRoles) {
            EmrVersionTree emrVersionTree = new EmrVersionTree();
            emrVersionTree.setId(emrVersionRole.getId());
            emrVersionTree.setCode(emrVersionRole.getRoleCode());
            emrVersionTree.setName(emrVersionRole.getRoleName());
            emrVersionTree.setType("1");
            if (itemMap.containsKey(emrVersionRole.getRoleCode())) {
                List<EmrVersionTree> emrVersionTrees = new ArrayList<>();
                for (EmrItem emrItem : itemMap.get(emrVersionRole.getRoleCode())) {
                    EmrVersionTree emrVersionTree1 = new EmrVersionTree();
                    emrVersionTree1.setId(emrItem.getId());
                    emrVersionTree1.setPCode(emrVersionRole.getRoleCode());
                    emrVersionTree1.setCode(emrItem.getItemCode());
                    emrVersionTree1.setName(emrItem.getItemName());
                    emrVersionTree1.setType("2");
                    emrVersionTrees.add(emrVersionTree1);
                }
                emrVersionTree.setChildren(emrVersionTrees);
            }
            list.add(emrVersionTree);
        }
        return Result.succ(1, "成功", list);
    }
}
